# -*- coding:utf8 -*-
__author__ = 'cosven'

import json

import flask
from flask.views import MethodView
from flask import render_template
from flask import g, request, redirect, url_for, flash
from blog import login_manager, mongo
from flask.ext.login import UserMixin, login_required, login_user, logout_user

from blog.controller.common import LOG


class User(UserMixin):
    def __init__(self, username):
        self.id = username

    @classmethod
    def get(cls, id):
        """
        :param str id: 实际上是用户名
        :return :返回一个user对象
        """
        user_entry = mongo.db.user.find_one({'username': id})
        if user_entry is not None:
            return User(id)
        else:
            return None

@login_manager.user_loader
def load_user(id):
    """
    login_required会自动调用该函数
    该函数从数据库去验证username，如果验证通过，返回user,也就是把这个user标定为登陆状态
    """
    return User.get(id)

def login():
    """
    这个函数将会被路由login调用
    验证username和password，返回json，flag设为True
    验证失败，返回json，flag设为False
    :return: 返回{‘flag’: boolean, 'message': string}
    """
    if request.method == "GET":
        return render_template('login.html')
    if request.method == "POST":
        form = request.form
        if form.has_key('username') and form.has_key('password'):
            id = form['username']
            pw = form['password']
            user_entry = mongo.db.user.find_one({'username': id, 'password': pw})
            if user_entry is not None:
                user = User(id)
                login_user(user)
                result = {'flag': True,
                          'message': 'Login Successful'}
                return redirect('/home')
            else:
                result = {'flag': False,
                          'message': 'Username or Password error'}
                return flask.jsonify(**result)
        else:
            result = {'flag': False, 'message': 'Hack failed'}
            return flask.jsonify(**result)
    else:
        return render_template('login.html')


@login_required
def logout():
    """
    处理用户登出
    :return:
    """
    logout_user()
    return redirect('/home')